using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
using System.Text.Json;
using CKY.AgentPlatform.PromptTemplates;

namespace CKY.AgentPlatform.Services
{
    /// <summary>
    /// Prompt模板服务 - 负责Prompt模板的应用和处理
    /// </summary>
    public class PromptTemplateService : ApplicationService, IPromptTemplateService
    {
        private readonly IRepository<PromptTemplate, Guid> _promptTemplateRepository;
        private readonly ILogger<PromptTemplateService> _logger;

        public PromptTemplateService(
            IRepository<PromptTemplate, Guid> promptTemplateRepository,
            ILogger<PromptTemplateService> logger)
        {
            _promptTemplateRepository = promptTemplateRepository;
            _logger = logger;
        }

        /// <summary>
        /// 应用Prompt模板
        /// </summary>
        /// <param name="templateId">模板ID</param>
        /// <param name="variables">变量字典</param>
        /// <returns>处理结果</returns>
        public async Task<PromptTemplateResult> ApplyTemplateAsync(Guid templateId, Dictionary<string, object> variables)
        {
            var processingId = Guid.NewGuid();
            _logger.LogInformation("开始应用Prompt模板: {TemplateId}, 处理ID: {ProcessingId}",
                templateId, processingId);

            try
            {
                // 获取模板
                var template = await _promptTemplateRepository.GetAsync(templateId);
                if (!template.IsActive)
                {
                    throw new InvalidOperationException($"Prompt模板未激活: {template.Name}");
                }

                // 应用模板处理
                var result = await ProcessTemplateAsync(template, variables);

                _logger.LogInformation("Prompt模板应用完成: {TemplateName}, 处理ID: {ProcessingId}, 成功: {Success}",
                    template.Name, processingId, result.IsSuccess);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Prompt模板应用异常: {TemplateId}, 处理ID: {ProcessingId}",
                    templateId, processingId);

                return new PromptTemplateResult
                {
                    IsSuccess = false,
                    ErrorMessage = ex.Message,
                    ProcessedPrompt = ""
                };
            }
        }

        /// <summary>
        /// 处理模板
        /// </summary>
        private async Task<PromptTemplateResult> ProcessTemplateAsync(PromptTemplate template, Dictionary<string, object> variables)
        {
            try
            {
                var templateContent = template.TemplateContent;
                var templateType = template.TemplateType;

                // 根据模板类型进行不同的处理
                var processedPrompt = templateType switch
                {
                    PromptTemplateType.SimpleText => await ProcessSimpleTextTemplateAsync(templateContent, variables),
                    PromptTemplateType.Mustache => await ProcessMustacheTemplateAsync(templateContent, variables),
                    PromptTemplateType.Liquid => await ProcessLiquidTemplateAsync(templateContent, variables),
                    PromptTemplateType.Handlebars => await ProcessHandlebarsTemplateAsync(templateContent, variables),
                    PromptTemplateType.JavaScript => await ProcessJavaScriptTemplateAsync(templateContent, variables),
                    _ => throw new NotSupportedException($"不支持的模板类型: {templateType}")
                };

                // 应用后处理规则
                processedPrompt = ApplyPostProcessingRules(template, processedPrompt);

                return new PromptTemplateResult
                {
                    IsSuccess = true,
                    ProcessedPrompt = processedPrompt,
                    Parameters = ExtractUsedVariables(variables)
                };
            }
            catch (Exception ex)
            {
                return new PromptTemplateResult
                {
                    IsSuccess = false,
                    ErrorMessage = ex.Message,
                    ProcessedPrompt = ""
                };
            }
        }

        /// <summary>
        /// 处理简单文本模板
        /// </summary>
        private async Task<string> ProcessSimpleTextTemplateAsync(string templateContent, Dictionary<string, object> variables)
        {
            await Task.Yield(); // 模拟异步操作

            var result = templateContent;

            // 简单的变量替换：{{variable_name}}
            var variablePattern = new Regex(@"\{\{(\w+)\}\}");
            var matches = variablePattern.Matches(result);

            foreach (Match match in matches)
            {
                var variableName = match.Groups[1].Value;
                if (variables.TryGetValue(variableName, out var value))
                {
                    result = result.Replace(match.Value, value?.ToString() ?? "");
                }
            }

            return result;
        }

        /// <summary>
        /// 处理Mustache模板
        /// </summary>
        private async Task<string> ProcessMustacheTemplateAsync(string templateContent, Dictionary<string, object> variables)
        {
            await Task.Yield(); // 模拟异步操作

            try
            {
                // 这里可以使用Mustache.NET库
                // 简化实现，只支持基本语法
                var result = templateContent;

                // 处理变量 {{variable}}
                result = ProcessMustacheVariables(result, variables);

                // 处理条件 {{#if condition}}...{{/if}}
                result = ProcessMustacheConditions(result, variables);

                // 处理循环 {{#each items}}...{{/each}}
                result = ProcessMustacheLoops(result, variables);

                return result;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Mustache模板处理失败", ex);
            }
        }

        /// <summary>
        /// 处理Liquid模板
        /// </summary>
        private async Task<string> ProcessLiquidTemplateAsync(string templateContent, Dictionary<string, object> variables)
        {
            await Task.Yield(); // 模拟异步操作

            try
            {
                // 这里可以使用DotLiquid库
                // 简化实现，只支持基本语法
                var result = templateContent;

                // 处理变量 {{ variable }}
                result = ProcessLiquidVariables(result, variables);

                // 处理条件 {% if condition %}...{% endif %}
                result = ProcessLiquidConditions(result, variables);

                // 处理循环 {% for item in items %}...{% endfor %}
                result = ProcessLiquidLoops(result, variables);

                return result;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Liquid模板处理失败", ex);
            }
        }

        /// <summary>
        /// 处理Handlebars模板
        /// </summary>
        private async Task<string> ProcessHandlebarsTemplateAsync(string templateContent, Dictionary<string, object> variables)
        {
            await Task.Yield(); // 模拟异步操作

            try
            {
                // 这里可以使用Handlebars.NET库
                // 简化实现，只支持基本语法
                var result = templateContent;

                // 处理变量 {{variable}}
                result = ProcessHandlebarsVariables(result, variables);

                // 处理条件 {{#if condition}}...{{/if}}
                result = ProcessHandlebarsConditions(result, variables);

                // 处理循环 {{#each items}}...{{/each}}
                result = ProcessHandlebarsLoops(result, variables);

                return result;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Handlebars模板处理失败", ex);
            }
        }

        /// <summary>
        /// 处理JavaScript模板
        /// </summary>
        private async Task<string> ProcessJavaScriptTemplateAsync(string templateContent, Dictionary<string, object> variables)
        {
            await Task.Yield(); // 模拟异步操作

            try
            {
                // 这里可以使用Jint等JavaScript引擎
                // 简化实现，只支持基本表达式
                var result = templateContent;

                // 处理JavaScript表达式 ${variable}
                result = ProcessJavaScriptExpressions(result, variables);

                return result;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("JavaScript模板处理失败", ex);
            }
        }

        /// <summary>
        /// 处理Mustache变量
        /// </summary>
        private string ProcessMustacheVariables(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{\{(\w+(?:\.\w+)*)\}\}");
            return ProcessVariablePattern(pattern, template, variables);
        }

        /// <summary>
        /// 处理Liquid变量
        /// </summary>
        private string ProcessLiquidVariables(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{\{\s*(\w+(?:\.\w+)*)\s*\}\}");
            return ProcessVariablePattern(pattern, template, variables);
        }

        /// <summary>
        /// 处理Handlebars变量
        /// </summary>
        private string ProcessHandlebarsVariables(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{\{(\w+(?:\.\w+)*)\}\}");
            return ProcessVariablePattern(pattern, template, variables);
        }

        /// <summary>
        /// 处理JavaScript表达式
        /// </summary>
        private string ProcessJavaScriptExpressions(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\$\{(\w+(?:\.\w+)*)\}");
            return ProcessVariablePattern(pattern, template, variables);
        }

        /// <summary>
        /// 处理通用变量模式
        /// </summary>
        private string ProcessVariablePattern(Regex pattern, string template, Dictionary<string, object> variables)
        {
            var result = template;
            var matches = pattern.Matches(result);

            foreach (Match match in matches)
            {
                var variablePath = match.Groups[1].Value;
                var value = GetNestedValue(variables, variablePath);
                result = result.Replace(match.Value, value?.ToString() ?? "");
            }

            return result;
        }

        /// <summary>
        /// 获取嵌套值
        /// </summary>
        private object GetNestedValue(Dictionary<string, object> variables, string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                return null;

            var parts = path.Split('.');
            object current = variables;

            foreach (var part in parts)
            {
                if (current is Dictionary<string, object> dict)
                {
                    if (dict.TryGetValue(part, out var value))
                    {
                        current = value;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }

            return current;
        }

        /// <summary>
        /// 处理Mustache条件
        /// </summary>
        private string ProcessMustacheConditions(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{\{#if\s+(\w+)\}\}(.*?)\{\{/if\}\}", RegexOptions.Singleline);
            return ProcessConditions(pattern, template, variables);
        }

        /// <summary>
        /// 处理Liquid条件
        /// </summary>
        private string ProcessLiquidConditions(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{%\s*if\s+(\w+)\s*%\}(.*?)\{%\s*endif\s*%\}", RegexOptions.Singleline);
            return ProcessConditions(pattern, template, variables);
        }

        /// <summary>
        /// 处理Handlebars条件
        /// </summary>
        private string ProcessHandlebarsConditions(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{\{#if\s+(\w+)\}\}(.*?)\{\{/if\}\}", RegexOptions.Singleline);
            return ProcessConditions(pattern, template, variables);
        }

        /// <summary>
        /// 处理通用条件模式
        /// </summary>
        private string ProcessConditions(Regex pattern, string template, Dictionary<string, object> variables)
        {
            var result = template;
            var matches = pattern.Matches(result);

            foreach (Match match in matches)
            {
                var variableName = match.Groups[1].Value;
                var content = match.Groups[2].Value;

                var shouldShow = variables.TryGetValue(variableName, out var value) &&
                               (value != null && !value.Equals(false) && !value.Equals(""));

                var replacement = shouldShow ? content : "";
                result = result.Replace(match.Value, replacement);
            }

            return result;
        }

        /// <summary>
        /// 处理Mustache循环
        /// </summary>
        private string ProcessMustacheLoops(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{\{#each\s+(\w+)\}\}(.*?)\{\{/each\}\}", RegexOptions.Singleline);
            return ProcessLoops(pattern, template, variables);
        }

        /// <summary>
        /// 处理Liquid循环
        /// </summary>
        private string ProcessLiquidLoops(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{%\s*for\s+(\w+)\s+in\s+(\w+)\s*%\}(.*?)\{%\s*endfor\s*%\}", RegexOptions.Singleline);
            return ProcessLoops(pattern, template, variables);
        }

        /// <summary>
        /// 处理Handlebars循环
        /// </summary>
        private string ProcessHandlebarsLoops(string template, Dictionary<string, object> variables)
        {
            var pattern = new Regex(@"\{\{#each\s+(\w+)\}\}(.*?)\{\{/each\}\}", RegexOptions.Singleline);
            return ProcessLoops(pattern, template, variables);
        }

        /// <summary>
        /// 处理通用循环模式
        /// </summary>
        private string ProcessLoops(Regex pattern, string template, Dictionary<string, object> variables)
        {
            var result = template;
            var matches = pattern.Matches(result);

            foreach (Match match in matches)
            {
                var itemName = match.Groups[1].Value;
                var collectionName = match.Groups.Count > 2 ? match.Groups[2].Value : itemName;
                var content = match.Groups[2].Value;

                if (variables.TryGetValue(collectionName, out var collection) && collection is System.Collections.IList list)
                {
                    var loopResult = "";
                    foreach (var item in list)
                    {
                        var itemContent = content;
                        var itemVariables = new Dictionary<string, object>
                        {
                            { itemName, item }
                        };

                        // 处理项目中的变量
                        itemContent = ProcessVariablePattern(
                            new Regex(@"\{\{" + itemName + @"\.(\w+)\}\}"),
                            itemContent,
                            new Dictionary<string, object>
                            {
                                { itemName, new Dictionary<string, object>() }
                            });

                        loopResult += itemContent;
                    }

                    result = result.Replace(match.Value, loopResult);
                }
                else
                {
                    result = result.Replace(match.Value, "");
                }
            }

            return result;
        }

        /// <summary>
        /// 应用后处理规则
        /// </summary>
        private string ApplyPostProcessingRules(PromptTemplate template, string processedPrompt)
        {
            var result = processedPrompt;

            // 1. 移除多余的空行
            result = Regex.Replace(result, @"\n\s*\n\s*\n", "\n\n");

            // 2. 去除首尾空白
            result = result.Trim();

            // 3. 应用最大长度限制
            if (template.MaxLength > 0 && result.Length > template.MaxLength)
            {
                result = result.Substring(0, template.MaxLength - 3) + "...";
            }

            // 4. 应用后处理脚本（如果有）
            if (!string.IsNullOrWhiteSpace(template.PostProcessingScript))
            {
                result = ApplyPostProcessingScript(result, template.PostProcessingScript);
            }

            return result;
        }

        /// <summary>
        /// 应用后处理脚本
        /// </summary>
        private string ApplyPostProcessingScript(string content, string script)
        {
            try
            {
                // 这里可以实现简单的脚本处理逻辑
                // 例如：文本替换、格式化等
                var lines = script.Split('\n');
                foreach (var line in lines)
                {
                    var trimmedLine = line.Trim();
                    if (string.IsNullOrWhiteSpace(trimmedLine) || trimmedLine.StartsWith("#"))
                        continue;

                    // 简单的替换规则：replace("old", "new")
                    if (trimmedLine.StartsWith("replace("))
                    {
                        var match = System.Text.RegularExpressions.Regex.Match(trimmedLine, @"replace\(""([^""]*)"",\s*""([^""]*)""\)");
                        if (match.Success)
                        {
                            var oldValue = match.Groups[1].Value;
                            var newValue = match.Groups[2].Value;
                            content = content.Replace(oldValue, newValue);
                        }
                    }
                }

                return content;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "后处理脚本执行失败");
                return content;
            }
        }

        /// <summary>
        /// 提取使用的变量
        /// </summary>
        private Dictionary<string, object> ExtractUsedVariables(Dictionary<string, object> variables)
        {
            var result = new Dictionary<string, object>();
            foreach (var variable in variables)
            {
                if (variable.Value != null)
                {
                    result[variable.Key] = variable.Value;
                }
            }
            return result;
        }

        /// <summary>
        /// 验证模板语法
        /// </summary>
        public async Task<bool> ValidateTemplateSyntaxAsync(Guid templateId)
        {
            try
            {
                var template = await _promptTemplateRepository.GetAsync(templateId);
                var testVariables = new Dictionary<string, object>
                {
                    { "test", "test_value" },
                    { "number", 42 },
                    { "boolean", true },
                    { "list", new[] { "item1", "item2" } }
                };

                await ProcessTemplateAsync(template, testVariables);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取模板预览
        /// </summary>
        public async Task<string> GetTemplatePreviewAsync(Guid templateId)
        {
            var template = await _promptTemplateRepository.GetAsync(templateId);
            var previewVariables = new Dictionary<string, object>
            {
                { "system_prompt", "这是一个系统提示词的示例" },
                { "user_input", "这是用户输入的示例" },
                { "agent_name", "示例Agent" },
                { "agent_description", "这是一个Agent的描述示例" }
            };

            var result = await ProcessTemplateAsync(template, previewVariables);
            return result.ProcessedPrompt;
        }

        /// <summary>
        /// 获取模板 - 实现IPromptTemplateService接口
        /// </summary>
        public async Task<string> GetTemplateAsync(Guid templateId)
        {
            var template = await _promptTemplateRepository.GetAsync(templateId);
            return template.Template;
        }

        /// <summary>
        /// 验证模板 - 实现IPromptTemplateService接口
        /// </summary>
        public async Task<bool> ValidateTemplateAsync(string template)
        {
            try
            {
                // 简单的模板验证
                if (string.IsNullOrWhiteSpace(template))
                    return false;

                // 检查基本的占位符语法
                var placeholders = System.Text.RegularExpressions.Regex.Matches(template, @"\{\{([^}]+)\}\}");
                return placeholders.Count >= 0; // 至少有占位符或者没有占位符
            }
            catch
            {
                return false;
            }
        }
    }
}